package goodash

import (
	"net"
)

// 获取本地ip
func GetFirstAvailableIP() (ip string, err error) {
	ips, err := GetAllLocalIPs()
	if err == nil {
		return ips[0], nil
	}
	return
}

func isValidIP(addr string) bool {
	ip := net.ParseIP(addr)
	return ip.IsGlobalUnicast() && !ip.IsInterfaceLocalMulticast()
}

// GetAllLocalIPs 获取所有本地IP地址
func GetAllLocalIPs() (ips []string, err error) {
	interfaces, err := net.Interfaces()
	if err != nil {
		return
	}
	var addrs []net.Addr
	for _, iface := range interfaces {
		if iface.Flags&net.FlagUp == 0 {
			continue
		}
		addrs, err = iface.Addrs()
		if err != nil {
			continue
		}

		for _, rawAddr := range addrs {
			var ip net.IP
			switch addr := rawAddr.(type) {
			case *net.IPAddr:
				ip = addr.IP
			case *net.IPNet:
				ip = addr.IP
			default:
				continue
			}
			if isValidIP(ip.String()) && !ip.IsLoopback() && ip.To4() != nil {
				ips = append(ips, ip.String())
			}
		}
	}

	return ips, nil
}
